<template>
  <div>
    <!-- 面包屑导区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- :to="{ path: '/homePage' }" -->
      <el-breadcrumb-item :to="{ path: '/homePage' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区 -->
    <el-card class="box-card">
      <div>
        <!-- 搜索 添加用户区 
          :gutter="20" 2个col之间的水平间距-->
        <el-row :gutter="20">
          <el-col :span="7">
            <el-input
              placeholder="请输入内容"
              v-model="queryUserParam.query"
              @clear="getUserList"
              clearable
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getUserList"
              ></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="openAddUser">添加用户</el-button>
          </el-col>
        </el-row>

        <!-- 表格数据区 -->
        <el-table :data="userList" :border="true" stripe>
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column
            prop="role_name"
            label="角色名称"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="create_time"
            label="创建时间"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="mobile"
            label="手机"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="email"
            label="邮箱"
            width="180"
          ></el-table-column>

          <el-table-column label="状态" width="180">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                active-color="##409eff"
                inactive-color="##eaecf0"
                @change="updateUserStatus(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <!-- @click="getUserDetail(scope.row.id)" -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="small"
                @click="getUserDetailV2(scope.row)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="removeByUserId(scope.row.id)"
              ></el-button>
              <el-tooltip
                effect="dark"
                content="分配角色"
                placement="top-start"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-star-off"
                  size="small"
                  @click="openSetRole(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryUserParam.pagenum"
          :page-sizes="[1, 3, 5, 7, 10]"
          :page-size="queryUserParam.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="30%"
      @closed="closeAddUserDialog"
    >
      <!-- <span>这是一段信息</span> -->
      <el-form
        :model="addUserForm"
        :rules="addUserFormRules"
        ref="addUserFormRef"
        label-width="100px"
      >
        <!-- 用户名 -->
        <el-form-item prop="username" label="用户名">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password" label="密码">
          <el-input v-model="addUserForm.password" type="password"></el-input>
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>

        <!-- 手机 -->
        <el-form-item prop="mobile" label="手机">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editUserDialogVisible"
      width="30%"
      @closed="closeEditUserDialog"
    >
      <el-form
        :model="editUserForm"
        :rules="editUserFormRules"
        ref="editUserFormRef"
        label-width="100px"
      >
        <el-form-item prop="id" v-if="false">
          <el-input v-model="editUserForm.id"></el-input>
        </el-form-item>

        <!-- 用户名 接口不支持修改用户名 -->
        <el-form-item prop="username" label="用户名">
          <el-input
            v-model="editUserForm.username"
            :disabled="editUserDialogVisible"
          ></el-input>
        </el-form-item>

        <!-- 密码 -->
        <!-- <el-form-item prop="password" label="密码">
          <el-input v-model="editUserForm.password" type="password"></el-input>
        </el-form-item> -->

        <!-- 邮箱 -->
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>

        <!-- 手机 -->
        <el-form-item prop="mobile" label="手机">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配用户角色对话框 -->
    <el-dialog
      title="分配用户角色"
      :visible.sync="setUserRoleDialogVisible"
      width="30%"
      @closed="closeUserRoleDialogVisible"
    >
      <div>
        <p>当前用户名称: &nbsp; {{ this.currentUser.username }}</p>
        <p>当前用户角色: &nbsp; {{ this.currentUser.role_name }}</p>
        <p>分配新角色: &nbsp;
          <el-select v-model="selectRoleId" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setUserRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkPhone = (rule, value, callback) => {
      // 手机号验证
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^1[3456789]\d{9}$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    };
    return {
      addUserForm: {},
      editUserForm: {},
      addUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, message: "长度在 5 个字符以上", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入正确的邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],

        mobile: [
          { required: true, message: "请输入正确的手机号码", trigger: "blur" },
          {
            validator: checkPhone,
            message: "请输入正确的手机号码",
            trigger: ["blur", "change"],
          },
        ],
      },

      editUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入正确的邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],

        mobile: [
          { required: true, message: "请输入正确的手机号码", trigger: "blur" },
          {
            validator: checkPhone,
            message: "请输入正确的手机号码",
            trigger: ["blur", "change"],
          },
        ],
      },

      dialogVisible: false,
      editUserDialogVisible: false,
      setUserRoleDialogVisible: false,
      keyWord: "",
      queryUserParam: {
        query: "",
        pagenum: 1,
        // 这个数据要与 page-sizes 一一对应, 如果不对应下面页码会有问题
        pagesize: 5,
      },
      userList: [],
      pagenum: 1,
      total: 1,
      

      currentUser: {},
      roleList: [],
      selectRoleId: ''
    };
  },
  methods: {
    async getUserDetail(userId) {
      this.editUserDialogVisible = true;
      // 'users/' + userId
      const { data: resData } = await this.$http.get(`users/${userId}`);
      if (resData.meta.status !== 200) {
        this.$message.error(resData.meta.msg);
        return;
      }
      this.editUserForm = resData.data;
    },

    getUserDetailV2(row) {
      this.editUserForm = row;
      this.editUserDialogVisible = true;
    },

    // 关闭对话框后,必须重置表格所有内容
    closeAddUserDialog() {
      this.$refs.addUserFormRef.resetFields();
    },

    closeEditUserDialog() {
      this.$refs.editUserFormRef.resetFields();
    },
    addUser() {
      this.$refs.addUserFormRef.validate(async (validateRes) => {
        if (!validateRes) return;
        const { data: resData } = await this.$http.post(
          "users",
          this.addUserForm
        );
        console.log(resData.meta.status);
        if (resData.meta.status !== 201)
          return this.$message.error(resData.meta.msg);
        this.$message.success(resData.meta.msg);
        this.getUserList();
        this.dialogVisible = false;
      });
    },

    editUser() {
      this.$refs.editUserFormRef.validate(async (validateRes) => {
        if (!validateRes) return;
        const { data: resData } = await this.$http.put(
          `users/${this.editUserForm.id}`,
          this.editUserForm
        );
        console.log(resData.meta.status);
        if (resData.meta.status !== 200) return this.$message.error("修改失败");
        this.$message.success("修改成功");
        this.getUserList();
        this.editUserDialogVisible = false;
      });
    },

    openAddUser() {
      this.dialogVisible = true;
      // 第1次打开时会有这样的问题，因此重置放到关闭事件当中去
      // if(this.$refs.addUserFormRef === undefined) return
      // this.$refs.addUserFormRef.resetFields();
    },

    async updateUserStatus(userData) {
      console.log("userData is console......");
      console.log(userData);
      const { data: resData } = await this.$http.put(
        `users/${userData.id}/state/${userData.mg_state}`
      );
      if (resData.meta.status !== 200) {
        this.$message.error(resData.meta.msg);
        // 修改失败,要改回原来的数据
        userData.mg_state = !userData.mg_state;
        return;
      }
      this.$message.success(resData.meta.msg);
      this.getUserList();
    },

    async getUserList() {
      const { data: resData } = await this.$http.get("users", {
        params: this.queryUserParam,
      });

      if (resData.meta.status !== 200)
        return this.$message.error(resData.meta.msg);

      // 防止出现 删除一条数据后,根据页码数分页查询得到数据为空,在pagenum大于1的情况下
      // 对pagenum 进行减一 然后再次查询
      if (resData.data.users.length === 0 && this.queryUserParam.pagenum > 1) {
        this.queryUserParam.pagenum = this.queryUserParam.pagenum - 1;
        this.getUserList();
      }

      this.userList = resData.data.users;
      this.pagenum = resData.data.pagenum;
      this.total = resData.data.total;
      console.log(resData.data.users);
      console.log("userList is " + this.userList);
      console.log("pagenum is " + this.pagenum);
      console.log("total is " + this.total);
    },

    handleSizeChange(newPageSize) {
      this.queryUserParam.pagesize = newPageSize;
      this.getUserList();
    },

    handleCurrentChange(newPage) {
      this.queryUserParam.pagenum = newPage;
      this.getUserList();
    },

    async removeByUserId(userId) {
      // this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(async () => {
      //   const { data: resData } = await this.$http.delete("users/" + userId);
      //   this.$message({
      //     type: 'success',
      //     message: '删除成功!'
      //   });
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消删除'
      //   });
      // }).finally(()=>{
      //   this.getUserList();
      // })

      //confirm / cancel
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      console.log("confirmResult is " + confirmResult);
      if (confirmResult === "cancel") return this.$message.info("已取消删除");

      const { data: resData } = await this.$http.delete("users/" + userId);
      if (resData.meta.status !== 200) this.$message.error(resData.meta.msg);
      this.$message.success(resData.meta.msg);
      this.getUserList();
    },

     async openSetRole(row) {
      
      // 缓存当前角色
      this.currentUser = row;

      const { data: resData } = await this.$http.get("roles");
      if (resData.meta.status !== 200)
        return this.$message.error(resData.meta.msg);
      this.roleList = resData.data;

      this.setUserRoleDialogVisible = true;
    },

    //关闭分配用户角色对话框
    closeUserRoleDialogVisible() {
      this.selectRoleId = ''
    },
    
    // 分配用户角色
    async setRole(){
     
      const { data: resData } = await this.$http.put(`users/${this.currentUser.id}/role`,
      {rid: this.selectRoleId});
      if (resData.meta.status !== 200) this.$message.error(resData.meta.msg);
      this.$message.success(resData.meta.msg);
      this.getUserList();
      this.setUserRoleDialogVisible = false;
    }
  },
  created() {
    this.getUserList();
  },
};
</script>

<style lang="less" scoped>
.el-form-item {
  margin-left: -48px;
}

.el-input {
  margin-left: -7px;
}
</style>